package com.jxcq.tensquare.friend.service;

import com.jxcq.tensquare.friend.dao.FriendDao;
import com.jxcq.tensquare.friend.dao.NoFriendDao;
import com.jxcq.tensquare.friend.pojo.Friend;
import com.jxcq.tensquare.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
@Transactional
public class FriendService {

    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    public int addFriend(String userid, String friengid) {
        //先判断userid-->friengid是否有数据，有则为重复添加，返回0
        Friend friend = friendDao.findByUseridAndFriendid(userid, friengid);
        if (friend != null) {
            return 0;
        }
        //添加好友userid-->friengid，其状态为0
        friend = new Friend();
        friend.setUserid(userid);
        friend.setFriendid(friengid);
        friend.setIslike("0");
        friendDao.save(friend);
        //判断friengid-->userid是否有数据，如果有，则把双向状态都改为1
        if (friendDao.findByUseridAndFriendid(friengid, userid) != null) {
            //把双方的islike都改为1
            friendDao.updateIsLike("1", userid, friengid);
            friendDao.updateIsLike("1", friengid, userid);
        }
        return 1;
    }

    public int addNoFriend(String userid, String friengid) {
        NoFriend noFriend = noFriendDao.findByUseridAndFriendid(userid, friengid);
        if (noFriend != null) {
            return 0;
        }
        noFriend = new NoFriend();
        noFriend.setUserid(userid);
        noFriend.setFriendid(friengid);
        noFriendDao.save(noFriend);
        return 1;
    }

    public void deleteFriend(String userid, String friendid) {
        //删除表中userid-->friendid这条数据
        friendDao.deleteFriend(userid, friendid);
        //更新friendid-->userid的islike为0
        friendDao.updateIsLike("0", friendid, userid);
        //非好友中添加数
        NoFriend noFriend = new NoFriend();
        noFriend.setUserid(userid);
        noFriend.setFriendid(friendid);
        noFriendDao.save(noFriend);
    }
}
